package com.example.forum.services.impl;

import com.example.forum.dao.UserMapper;
import com.example.forum.exception.ApplicationException;
import com.example.forum.model.Board;
import com.example.forum.model.User;
import com.example.forum.services.IUserService;
import com.example.forum.utils.MD5Util;
import com.example.forum.utils.StringUtil;
import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import com.example.forum.utils.UUIDUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @Author YJ
 * @Date 2023/8/16 9:13
 * Description:实现业务代码
 */
@Slf4j
@Service
public class UserServiceImpl implements IUserService {
    @Resource
    private UserMapper userMapper;

    @Override
    public void createNormalUser(User user) {
        //1.非空校验
        if (user == null || StringUtil.isEmpty(user.getNickname())
                || StringUtil.isEmpty(user.getUsername())
                || StringUtil.isEmpty(user.getPassword())
                || StringUtil.isEmpty(user.getSalt())) {
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常，统一抛出Application异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //2.按用户名查询用户信息
        User existsUser = userMapper.selectByUserName(user.getUsername());
        //2.1判断用户是否存在
        if (existsUser != null) {
            //打印日志
            log.info(ResultCode.AILED_USER_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.AILED_USER_EXISTS));
        }
        //3.新增用户，设置默认值
        user.setGender((byte) 2);
        user.setArticleCount(0);
        user.setIsAdmin((byte) 0);
        user.setState((byte) 0);
        user.setDeleteState((byte) 0);
        //当前日期
        Date date = new Date();
        user.setCreateTime(date);
        user.setUpdateTime(date);
        //写入数据库
        int row = userMapper.insertSelective(user);
        if (row != 1) {
            //打印日志
            log.info(ResultCode.FAILED_CREATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
        //打印新增成功日志
        log.info("新增用户成功. username = " + user.getUsername() + ". ");
    }

    @Override
    public User selectByUserName(String username) {
        //非空校验
        if (StringUtil.isEmpty(username)) {
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //返回查询结果
        return userMapper.selectByUserName(username);
    }

    @Override
    public User Login(String username, String password) {
        if (StringUtil.isEmpty(username) || StringUtil.isEmpty(password)) {
            //打印日志
            log.warn(ResultCode.FAILED_LOGIN.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }
        //按用户名查询用户信息
        User user = selectByUserName(username);
        if (user == null) {
            //打印日志
            log.warn(ResultCode.FAILED_LOGIN.toString() + ", username = " + username);
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }
        //校验密码
        String ciphertext = MD5Util.md5Salt(password, user.getSalt());
        //密文和数据库存储的密码比较
        if (!ciphertext.equalsIgnoreCase(user.getPassword())) {
            //打印日志
            log.warn(ResultCode.FAILED_LOGIN.toString() + ", 密码错误, username = " + username);
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }
        //登录成功日志
        log.info("登录成功 username : " + username);
        //登陆成功，返回用户信息
        return user;
    }

    @Override
    public User selectById(Long id) {
        if (id == null) {
            //打印日志
            log.warn(ResultCode.FAILED_LOGIN.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }
        //调用dao查询数据库获取对象
        User user = userMapper.selectByPrimaryKey(id);
        //返回结果
        return user;
    }

    @Override
    public void addOneArticleCountByID(Long id) {
        if (id == null || id <= 0) {
            log.warn(ResultCode.FAILED_BOARD_ARTICLE_COUNT.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_ARTICLE_COUNT));
        }
        //查询用户信息
        User user = userMapper.selectByPrimaryKey(id);
        if (user == null) {
            log.warn(ResultCode.ERROR_IS_NULL.toString() + ", user id = " + id);
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }
        //更新帖子数量
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setArticleCount(user.getArticleCount() + 1);
        //更新数据库
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        //判断结果是否成功
        if (row != 1) {
            log.warn(ResultCode.FAILED.toString() + ", 受影响的行数不等于1");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
        log.info(ResultCode.SUCCESS.toString() + " user id = " + updateUser.getId()
                + ", article count = " + updateUser.getArticleCount()
                + ", user name = " + updateUser.getUsername());
    }

    @Override
    public void subOneArticleCountByID(Long id) {
        if (id == null || id <= 0) {
            log.warn(ResultCode.FAILED_BOARD_ARTICLE_COUNT.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_ARTICLE_COUNT));
        }
        //查询用户信息
        User user = userMapper.selectByPrimaryKey(id);
        if (user == null) {
            log.warn(ResultCode.ERROR_IS_NULL.toString() + ", user id = " + id);
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }
        //更新帖子数量
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setArticleCount(user.getArticleCount() - 1);
        //判断-1后用户的发帖数是否小于0
        if (updateUser.getArticleCount() < 0) {
            updateUser.setArticleCount(0);
        }
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        //判断结果是否成功
        if (row != 1) {
            log.warn(ResultCode.FAILED.toString() + ", 受影响的行数不等于1");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }

    @Override
    public void modifyInfo(User user) {
        //1.非空校验
        if (user == null || user.getId() == null || user.getId() <= 0) {
            log.warn(ResultCode.ERROR_IS_NULL.toString() + ", user id = " + user.getId());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }
        //2.校验用户是否存在
        User existsUser = userMapper.selectByPrimaryKey(user.getId());
        if (existsUser == null) {
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        //3.定义一个标志位
        boolean checkAttr = false;
        //4.用来更新的对象，防止用户传入的对象设置了其他属性
        User updateUser = new User();
        //5.设置用户id
        updateUser.setId(user.getId());
        //6.对每个参数进行校验
        if (!StringUtil.isEmpty(user.getUsername())
                && !user.getUsername().equals(existsUser.getUsername())) {
            //需要更新用户名（登录名）时，进行唯一性校验
            User checkUser = userMapper.selectByUserName(user.getUsername());
            if (checkUser != null) {
                log.warn(ResultCode.AILED_USER_EXISTS.toString());
                throw new ApplicationException(AppResult.failed(ResultCode.AILED_USER_EXISTS));
            }
            //数据库中没有重复用户，表示需要修改
            updateUser.setUsername(user.getUsername());
            //更新标志位
            checkAttr = true;
        }
        //7.校验昵称
        if (!StringUtil.isEmpty(user.getNickname())
                && !user.getNickname().equals(existsUser.getNickname())) {
            //更新
            updateUser.setNickname(user.getNickname());
            checkAttr = true;
        }
        //8.校验性别
        if (user.getGender() != null && user.getGender() != existsUser.getGender()) {
            //更新
            updateUser.setGender(user.getGender());
            //校验合法性
            if (updateUser.getGender() > 2 || updateUser.getGender() < 0) {
                updateUser.setGender((byte) 2);
            }
            checkAttr = true;
        }
        //9.校验邮箱
        if (!StringUtil.isEmpty(user.getEmail())
                && !user.getEmail().equals(existsUser.getEmail())) {
            //更新
            updateUser.setEmail(user.getEmail());
            checkAttr = true;
        }
        //10.校验电话号码
        if (!StringUtil.isEmpty(user.getPhoneNum())
                && !user.getPhoneNum().equals(existsUser.getPhoneNum())) {
            //更新
            updateUser.setPhoneNum(user.getPhoneNum());
            checkAttr = true;
        }
        //11.校验个人简介
        if (!StringUtil.isEmpty(user.getRemark())
                && !user.getRemark().equals(existsUser.getRemark())) {
            //更新
            updateUser.setRemark(user.getRemark());
            checkAttr = true;
        }
        //判断标志位
        if (checkAttr == false) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //设置更新时间
        updateUser.setUpdateTime(new Date());
        //调用dao
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if (row != 1) {
            log.warn(ResultCode.FAILED.toString() + ", 受影响的行数不等于1");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }

    @Override
    public void modifyPassword(Long id, String oldPassword, String newPassword ) {
        //非空校验
        if (id == null || id <= 0 || StringUtil.isEmpty(newPassword) || StringUtil.isEmpty(oldPassword)) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //查询用户信息
        User user = userMapper.selectByPrimaryKey(id);
        if(user == null || user.getState() == 1) {
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        //校验老密码是否正确
        //对老密码进行加密获取密文
        String oldEncryptPassword = MD5Util.md5Salt(oldPassword, user.getSalt());
        //与数据库中用户密码进行比较
        if(!oldEncryptPassword.equalsIgnoreCase(user.getPassword())) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //生成新密码的盐
        String salt = UUIDUtil.UUID_32();
        String encryptPassword = MD5Util.md5Salt(newPassword,salt);
        //构造要更新的对象
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setSalt(salt);
        updateUser.setPassword(encryptPassword);
        updateUser.setUpdateTime(new Date());
        //调用dao
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if( row != 1) {
            log.warn(ResultCode.FAILED.toString() + ", 受影响的行数不等于1");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }
}
